<template>
  <div>
    <el-card class="box-card">
      <el-button v-has="'btn.Trademark.add'" type="primary" size="default" icon="Plus" @click="addTradeMark">添加品牌</el-button>
      <el-table class="table-box" border :data="trademarkArr">
        <el-table-column type="index" label="序号" width="80px" align="center" />
        <el-table-column props="tmName" label="品牌名称">
          <template #default="{ row }">
            <span style="color: 409EFF">
              {{ row.tmName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column props="logoUrl" label="品牌Logo">
          <template #default="{ row }">
            <el-image style="width: 100px; height: 100px" :src="row.logoUrl" fit="cover" :preview-src-list="[row.logoUrl]" />
          </template>
        </el-table-column>
        <el-table-column props="tmName" label="品牌操作">
          <template #default="{ row }">
            <el-button v-has="'btn.Trademark.update'" type="warning" size="small" icon="Edit" @click="updataTradeMark(row)" />
            <el-popconfirm :title="`您确认要删除${row.tmName}吗？`" width="200px" icon="Delete" @confirm="removeTradeMark(row.id)">
              <template #reference>
                <el-button v-has="'btn.Trademark.remove'" type="danger" size="small" icon="Delete" />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:page-size="limit" v-model:current-page="pageNo" class="pagination" :page-sizes="[3, 5, 7, 9]" size="large" :background="true" layout="prev, pager, next, jumper,->, sizes,total" :total="total" @change="changePageNo" />
    </el-card>
    <el-dialog v-model="dialogVisible" :title="tradeMarkForm.id ? '修改品牌' : '添加品牌'" width="500" :before-close="handleClose">
      <!-- tradeMark表单 -->
      <el-form ref="ruleFormRef" :model="tradeMarkForm" label-width="auto" class="demo-ruleForm" status-icon :rules="rules">
        <el-form-item label="品牌名称" prop="tmName" label-width="100px">
          <el-input v-model="tradeMarkForm.tmName" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl" label-width="100px">
          <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false" :before-upload="beforeAvatarUpload" :on-success="handleImageSuccess">
            <img v-if="tradeMarkForm.logoUrl" :src="tradeMarkForm.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><UploadFilled /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="confirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from 'vue';
import { reqHasTrademark, reqAddOrUpdateTrademark, reqDeleteTrademark } from '@/api/product/trademark';
import type { Records, TradeMark } from '@/api/product/trademark/type';
import { ElMessage, type UploadProps } from 'element-plus';

let pageNo = ref<number>(1);
let limit = ref<number>(3);
//存储上一次的页面数量，当页面数量发生改变，重置页数为1
let last_limit = ref<number>(3);

let total = ref<number>(0);

let trademarkArr = ref<Records>([]);

//获取已有品牌
const getTrademark = async () => {
  let result = await reqHasTrademark(pageNo.value, limit.value);
  if (result.code === 200) {
    total.value = result.data.total;
    trademarkArr.value = result.data.records;
  }
};

onMounted(() => {
  getTrademark();
});

// 表单页面节流阀
let loading = ref<boolean>(false);

const changePageNo = async (currentPage: number, pageSize: number) => {
  if (loading.value) return;
  loading.value = true;
  if (last_limit.value === pageSize) {
    pageNo.value = currentPage;
  } else {
    pageNo.value = 1;
    last_limit.value = pageSize;
  }

  await getTrademark();
  loading.value = false;
};
// 控制弹窗显隐
let dialogVisible = ref<boolean>(false);
// 添加|修改品牌表单参数
let tradeMarkForm = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
});
//添加品牌按钮点击事件
const addTradeMark = () => {
  tradeMarkForm.id = 0;
  tradeMarkForm.tmName = '';
  tradeMarkForm.logoUrl = '';

  dialogVisible.value = true;
  //清空错误信息方法1
  nextTick(() => {
    ruleFormRef.value.clearValidate('tmName');
    ruleFormRef.value.clearValidate('logoUrl');
  });
};
// 更新品牌按钮点击事件
const updataTradeMark = (row: TradeMark) => {
  Object.assign(tradeMarkForm, row);
  //清空错误信息方法2
  ruleFormRef.value?.clearValidate('tmName');
  ruleFormRef.value?.clearValidate('logoUrl');
  dialogVisible.value = true;
};
// 弹窗关闭事件
const handleClose = () => {
  dialogVisible.value = false;
};

let ruleFormRef = ref();
// 弹窗确定提交时间
const confirm = async () => {
  if (loading.value) return;
  loading.value = true;
  try {
    await ruleFormRef.value.validate();
  } catch {
    return;
  }

  let result: any = await reqAddOrUpdateTrademark(tradeMarkForm);
  let type: string = '添加';
  if (tradeMarkForm.id) {
    type = '修改';
  }
  if (result.code === 200) {
    dialogVisible.value = false;

    ElMessage({
      type: 'success',
      message: type + '品牌成功',
    });
    getTrademark();
  } else {
    ElMessage({
      type: 'error',
      message: type + '品牌失败',
    });
  }
  loading.value = false;
};
//图片上传前的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage.error('文件大小不能超过4M');
      return false;
    }
  } else {
    ElMessage.error('上传文件格式务必是PNG|JPG|GIF');
    return false;
  }
};

//图片上传成功后的钩子
const handleImageSuccess: UploadProps['onSuccess'] = (response, _uploadFile) => {
  tradeMarkForm.logoUrl = response.data;
  ruleFormRef.value.clearValidate('logoUrl');
};

// 品牌名称校验
const validatorTmName = (_rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback();
  } else {
    callback(new Error('品牌名称位数大于等于两位'));
  }
};

// 上传图片校验
const validatorLogoUrl = (_rule: any, value: any, callback: any) => {
  if (value) {
    callback();
  } else {
    callback(new Error('LOGO图片务必上传'));
  }
};

// 表单校验
const rules = {
  tmName: [
    {
      required: true,
      trigger: 'blur',
      validator: validatorTmName,
    },
  ],
  logoUrl: [
    {
      required: true,
      validator: validatorLogoUrl,
    },
  ],
};

//删除品牌气泡框回调
const removeTradeMark = async (id: number) => {
  let result = await reqDeleteTrademark(id);
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    });
    if (trademarkArr.value.length <= 1) {
      pageNo.value -= 1;
    }
    getTrademark();
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败',
    });
  }
};
</script>

<style lang="scss" scoped>
.table-box {
  margin-top: 10px;
}
.pagination {
  margin-top: 10px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
